package com.qingcloud.adminbackend.config;


import com.alibaba.fastjson.JSON;
import com.qingcloud.adminbackend.utils.CookieUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
//@Order(-1)
@Component
public class WebLogAspect {

//    @Resource
//    private AccessLogService accessLogService;

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("execution(* com.qingcloud.adminbackend.controller..*.*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容 获取用户信息/存储到数据库
        String userName = CookieUtil.getUserName(request);
        if (StringUtils.isEmpty(userName)) {
            userName = "anonymousUser";
        }
        logger.debug("{} {} {}", userName, JSON.toJSONString(request.getParameterMap()), request.getServletPath());
//        AccessLogDTO accessLogDTO = new AccessLogDTO();
//        accessLogDTO.setUserName(userName);
//        accessLogDTO.setAccessTime(new Date());
//        accessLogDTO.setFunctionUrl(request.getServletPath());
//        accessLogDTO.setRemoteAddr(RequestUtil.getRemoteIp(request));
//        accessLogService.save(accessLogDTO);
    }
}
